package com.dianrui.qiyouriding.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.MyApplication;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.util.BitmapUtils;
import com.dianrui.qiyouriding.util.ConvertUtils;
import com.dianrui.qiyouriding.util.GlideUtil;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.util.NoDoubleClickUtils;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.dianrui.qiyouriding.view.ninegride.NineView;
import com.dianrui.qiyouriding.view.ninegride.RatioImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

@SuppressWarnings("ALL")
public class FeedBackActivity extends BaseActivity implements NineView.NineViewShowCallBack {
    private List<String> imageList = new ArrayList<>();

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.input)
    EditText input;
    @BindView(R.id.sub_feedback)
    Button subFeedback;
    @BindView(R.id.editor_font_count)
    TextView editorFontCount;
    @BindView(R.id.nine)
    NineView nine;

    @Override
    public int getContentViewId() {
        return R.layout.activity_feedback;
    }

    @Override
    public void initView() {
        customInit(true, R.color.main_color);
        title.setText(getString(R.string.feed_txt));
        imageList.add("default");
        checkLocationPerssions();
        nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(6).setNineViewShowCallBack(this).setUrlList(imageList);
        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (s.length() == 140) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
                    }
                }

                if (text.length() > 0) {
                    subFeedback.setEnabled(true);
                    subFeedback.setBackgroundResource(R.drawable.blue_shape);
                } else {
                    subFeedback.setBackgroundResource(R.drawable.gray_shape);
                }
                editorFontCount.setText(text.length() + getString(R.string.feed_txt5));
            }
        });
    }

    //检查是否开启定位权限,有其故意关闭权限进入APP后也要有权限提醒设置
    private void checkLocationPerssions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }

        }

    }

    @Override
    public void initData() {}


    @OnClick({R.id.back, R.id.sub_feedback})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sub_feedback:
                if (StringUtils.isEmpty(input.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.feed_txt4));
                } else {
                    startFeedBack();
                }
                break;
                default:
                    break;
        }
    }

    private void startFeedBack() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList.size(); i++) {
            if (!"default".equals(imageList.get(i))) {
                jsonArray.put(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(imageList.get(i), 480, 960)));
            }

        }
        showLoadingDialog(getString(R.string.user_submiting));
        try {
            JSONObject jsonObject = new JSONObject();
            if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                jsonObject.put("member_id", SPUtils.getInstance().getString("member_id"));
            }
            jsonObject.put("content", input.getText().toString().trim());
            jsonObject.put("photo", jsonArray);
            OkHttpRequest.getInstance().postRequests(Url.FEEDBACK, jsonObject.toString(),  new OkHttpRequest.XCallBack() {
                @Override
                public void onResponse(String response) {
                    if (!StringUtils.isEmpty(response)) {
                        try {
                            final JSONObject datajsonObject = new JSONObject(response);
                            if (null != datajsonObject &&!isFinishing()) {
                                if (Constant.DATASUCCESS.equals(datajsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    ToastUtil.showToast(datajsonObject.optString("message"));
                                    finish();
                                } else {
                                   dismissLoadingDialog();
                                    ToastUtil.showToast(datajsonObject.optString("message"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onDisplayOneImage(RatioImageView imageView, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, FeedBackActivity.this, R.mipmap.add_photo));
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, FeedBackActivity.this));
        }
    }

    @Override
    public void onDisplayImage(RatioImageView imageView, RatioImageView closeButton, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, FeedBackActivity.this, R.mipmap.add_photo));
            if (closeButton != null) {
                closeButton.setVisibility(View.GONE);
            }
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, FeedBackActivity.this));
            if (closeButton != null) {
                closeButton.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList, Context context) {
        if ("default".equals(url)) {
            int count = 9;
            if (imageList.size() > 1) {
                count = 9 - imageList.size() + 1;
            }
            MyUtil.createPhotoChooseDialog(0, count, FeedBackActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
                @Override
                public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                    if (resultList == null || resultList.size() == 0) {
                        return;
                    }

                    for (int i = 0; i < imageList.size(); i++) {
                        if ("default".equals(imageList.get(i))) {
                            imageList.remove(i);
                        }
                    }
                    for (int i = 0; i < resultList.size(); i++) {
                        imageList.add(resultList.get(i).getPhotoPath());
                    }
                    if (imageList.size() < 9) {
                        imageList.add("default");
                    }
                    nine.urlList(imageList);

                }

                @Override
                public void onHanlderFailure(int requestCode, String errorMsg) {
                }
            });
        } else {
            List<String> temp = new ArrayList<>();
            int count = 0;
            for (int i = 0; i < imageList.size(); i++) {
                if (!"default".equals(imageList.get(i))) {
                    temp.add(imageList.get(i));
                } else {
                    count++;
                }
            }
            startActivity(new Intent(FeedBackActivity.this, BigImageActivity.class)
                    .putStringArrayListExtra("data", (ArrayList<String>) temp)
                    .putExtra("current", position));
        }
    }

    @Override
    public void onClickImageColse(int position, String url, List<String> urlList, Context context) {
        imageList.remove(position);
        int count = 0;
        for (int i = 0; i < imageList.size(); i++) {
            if ("default".equals(imageList.get(i))) {
                count++;
            }
        }
        if (count == 0) {
            imageList.add("default");
        }

        nine.urlList(imageList);
    }

    @Override
    public void onSamePhotos(List<String> mRejectUrlList) {}
}
